import React, { useRef, memo, useEffect, useState } from 'react';
import { Row, Col, Form, Button, MessagePlugin, Select, Input } from 'tdesign-react';
import { FormInstanceFunctions, SubmitContext } from 'tdesign-react/es/form/type';
import { useLocation, useNavigate } from 'react-router-dom';
import PubSub from 'pubsub-js';
import {
  ROOM_STATUS_OPTIONS,
  ROOM_SORT_FIELD_OPTIONS,
  ROOM_SORT_ORDER_OPTIONS,
  RoomSearchFormValues
} from '../consts';
const { FormItem } = Form;

export type RoomSearchFormProps = {
  onCancel: () => void;
  onSubmit: (values: RoomSearchFormValues) => void;
  floorList?: string[];
  onAdd?: () => void;
};

const RoomSearchForm: React.FC<RoomSearchFormProps> = (props) => {
  const formRef = useRef<FormInstanceFunctions>();
  const location = useLocation();
  const navigate = useNavigate();
  const [path, setPath] = useState<string>('');
  // 订阅当前的路由
  PubSub.subscribe('listPath', (msg, data) => {
    setPath(data)
  });

  // 解析 URL 中的查询参数
  const getQueryParams = () => {
    const params = new URLSearchParams(location.search);
    return {
      searchText: params.get('searchText') || '',
      status: params.get('status') || '',
      sortBy: params.get('sortBy') || '',
      sortOrder: params.get('sortOrder') || '',
      floorNumber: params.get('floorNumber') || '',
      page: params.get('page') || 1,
      pageSize: params.get('pageSize') || 10,
    };
  };

  // 初始化时从 URL 回显查询参数到表单
  useEffect(() => {
    const queryParams = getQueryParams();
    formRef.current?.setFieldsValue?.(queryParams);
  }, [location.search]);

  // 提交时同步参数到 URL
  const onSubmit = (e: SubmitContext) => {
    if (e.validateResult === true) {
      const formValues = formRef.current?.getFieldsValue?.(true) || {};
      // 构建查询字符串
      const params = new URLSearchParams();
      Object.entries(formValues).forEach(([key, value]) => {
        if (value) {
          params.set(key, value as string);
        }
      });
      navigate({ search: params.toString() }, { replace: true });
      props.onSubmit(formValues as RoomSearchFormValues);
      MessagePlugin.success('查询成功');
    }
  };

  // 重置时清空 URL 参数
  const onReset = () => {
    formRef.current?.reset();
    navigate({ search: '' }, { replace: true });
    props.onCancel();
    MessagePlugin.success('重置成功');
  };

  return (
    <div className='list-common-table-query'>
      <Form ref={formRef} onSubmit={onSubmit} onReset={onReset} labelWidth={80} colon>
        <Row>
          <Col flex='1'>
            <Row gutter={[12, 12]}>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='搜索' name='searchText'>
                  <Input placeholder='请输入包间号' style={{ width: '100%' }} />
                </FormItem>
              </Col>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='状态' name='status'>
                  <Select options={ROOM_STATUS_OPTIONS} placeholder='请选择状态' />
                </FormItem>
              </Col>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='排序字段' name='sortBy'>
                  <Select options={ROOM_SORT_FIELD_OPTIONS} placeholder='请选择排序字段' />
                </FormItem>
              </Col>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='排序方式' name='sortOrder'>
                  <Select options={ROOM_SORT_ORDER_OPTIONS} placeholder='请选择排序方式' />
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col flex='280px'>
            <Button theme='primary' type='submit' style={{ margin: '0px 20px' }}>
              查询
            </Button>
            <Button type='reset' variant='base' theme='default' style={{ position: "relative", margin: '0px 20px 0 0' }}>
              重置
            </Button>
            <Button theme='primary' onClick={props.onAdd}>
              新建包间
            </Button>
          </Col>
        </Row>
      </Form>
    </div>
  );
};

export default memo(RoomSearchForm);
